package com.ztools.mvp.proxy.impl;


import com.blankj.utilcode.util.LogUtils;
import com.ztools.mvp.IPresenter;
import com.ztools.mvp.IView;
import com.ztools.mvp.proxy.MvpBindCallback;

/**
 * Created by zhangxuehui on 2018/3/13.
 */

public class MvpBindCallbackProxy<V extends IView, P extends IPresenter<V>> implements MvpBindCallback<V, P> {
    //在代理类中，通过接口获取具体实现类的引用。
    private MvpBindCallback<V, P> mTargetCallback;

    public MvpBindCallbackProxy(MvpBindCallback<V, P> targetCallback) {
        this.mTargetCallback = targetCallback;
    }

    @Override
    public P newPresenter() {
        P p = this.mTargetCallback.getPresenter();
        if (p == null) {
            p = this.mTargetCallback.newPresenter();
            setPresenter(p);
        }
        if (p == null) {
            throw new NullPointerException(this.mTargetCallback.getClass().getSimpleName() + "====>空指针异常");
        }
        return p;
    }

    @Override
    public P getPresenter() {
        P p = this.mTargetCallback.getPresenter();
        if (p == null) {
            throw new NullPointerException(this.mTargetCallback.getClass().getSimpleName() + "====>空指针异常");
        }
        return p;
    }

    @Override
    public void setPresenter(P p) {
        this.mTargetCallback.setPresenter(p);
    }

    @Override
    public V newMvpView() {
        V v = this.mTargetCallback.getMvpView();
        if (v == null) {
            v = this.mTargetCallback.newMvpView();
            setMvpView(v);
        }
        if (v == null) {
            throw new NullPointerException(this.mTargetCallback.getClass().getSimpleName() + "====>空指针异常");
        }
        return v;
    }

    @Override
    public V getMvpView() {
        V v = this.mTargetCallback.getMvpView();
        if (v == null) {
            throw new NullPointerException(this.mTargetCallback.getClass().getSimpleName() + "====>空指针异常");
        }
        return v;
    }

    @Override
    public void setMvpView(V v) {
        this.mTargetCallback.setMvpView(v);
    }

    /**
     * 绑定view
     */
    public void attachView() {
        if(getMvpView()==null){
            LogUtils.e("MVP is MvpBindCallbackProxy attachView() NULL");
        }
        getPresenter().onAttachView(getMvpView());
    }

    /**
     * 解绑view
     */
    public void detachView() {
        getPresenter().onDetachView();
    }
}
